package com.wechet.aspect;

import com.sun.org.apache.xpath.internal.operations.String;
import com.wechet.common.CookieUtil;
import com.wechet.common.RedisConst;
import com.wechet.exception.AuthException;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.sasl.SaslException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by sc on 2017/9/29.
 */
@Aspect
@Component
public class SellerAutho {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.wechet.controller.Seller*.*(..))" +
            "&& !execution(public * com.wechet.controller.SellerUserController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doverify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //查询cookie
        Cookie cookie = CookieUtil.get(request, "token");
        if (cookie == null) {
            throw new AuthException();
        }

        java.lang.String tokenValue = redisTemplate.opsForValue().get(java.lang.String.format(RedisConst.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            throw new AuthException();
        }
    }
}
